package com.wp.file.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wp.file.common.BaseContext;
import com.wp.file.common.R;
import com.wp.file.pojo.Recycle;
import com.wp.file.pojo.User;
import com.wp.file.pojo.Warehouse;
import com.wp.file.pojo.vo.Share;
import com.wp.file.service.RecycleService;
import com.wp.file.service.UserService;
import com.wp.file.service.WarehouseService;
import com.wp.file.utils.EmailUtil;
import com.wp.file.utils.JwtTool;
import com.wp.file.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private RecycleService recycleService;

    @PostMapping("/sendmsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession){
        String subject = "寻真网盘登录验证码";//邮件标题
        if(StringUtils.isBlank(user.getEmail()) || !EmailUtil.checkEmail(user.getEmail())){
            return R.error("邮箱格式错误!");
        }
        String code = ValidateCodeUtils.generateValidateCode(4).toString();//获取四位数验证码
        String context = "【寻真云盘】验证码为："+code+" ,五分钟内有效。如非本人操作，请忽略。";
        //发送邮箱验证码
        userService.sendMsg(user.getEmail(), subject, context);
        redisTemplate.opsForValue().set(user.getEmail(), code, 5, TimeUnit.MINUTES);
        log.info("code={}",code);
        return R.success("发送验证码成功!");
    }


    @PostMapping("/login")
    public R<String> useLogin(@RequestBody Map map,HttpSession session,HttpServletResponse response){
        log.info("开始登录:"+map.toString());
        String email = (String)map.get("email");
        String code = (String)map.get("code");
        //从Redis中获取缓存的验证码
        Object codeReal = redisTemplate.opsForValue().get(email);
        if(codeReal==null) return R.error("验证码系统出错!");
        //查看邮箱名是否为空 或 不符合邮箱格式时
        if(StringUtils.isBlank(email) || !EmailUtil.checkEmail(email)){
            return R.error("邮箱格式错误");
        }
        //比对验证码
        if(!code.equals(codeReal)){
            //不相等的时候
            return R.error("登录失败,验证码错误!");
        }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getEmail,email);
        User userOne = userService.getOne(lqw);
        if (userOne == null){
            //没账号的时候创建并存入数据库
            User user = new User();user.setEmail(email);
            userService.save(user);
            userOne = user;
        }
        //登录成功 生成token返回
        Map<String,String> tmap = new HashMap<>();
        tmap.put("userId",userOne.getId().toString());
        tmap.put("email",email);
        log.info(userOne.getId().toString());
        String token = JwtTool.getJWT(tmap);
        response.setHeader("Authorization",token);
        //删除验证码
        redisTemplate.delete(email);
        //设置token有效期
        redisTemplate.opsForValue().set(email+"Authorization",token,1,TimeUnit.DAYS);
        return R.success("欢迎登录成功"+email);
    }


    /**
     * 退出登录
     * @param
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(@RequestHeader("Authorization") String auth){
        String email = JwtTool.parseJWT(auth).getClaims().get("email").asString();
        redisTemplate.delete(email+"Authorization");
        return R.success(email+"退出成功!");
    }

    /**
     * 获取用户信息
     * @param auth
     * @return
     */
    @GetMapping("/getinfo")
    public R<String> getInfo(@RequestHeader("Authorization") String auth){
        String email = JwtTool.parseJWT(auth).getClaims().get("email").asString();
        return R.success(email);
    }

    @GetMapping("/display")
    public R<Map> getUserStatus(){
        String keyPattern = "*Authorization";
        Set<String> keys = redisTemplate.keys(keyPattern);
        int count = keys.size();
        Map<String,Object> map = new HashMap<>();
        map.put("onlineNum",count);//在线人数
        List<Share> values = redisTemplate.opsForHash().values(BaseContext.getCurrentId().toString());
        int size = values.size();
        map.put("shareNum",size);//分享文件数
        LambdaQueryWrapper<Warehouse> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Warehouse::getUserId,BaseContext.getCurrentId());
        int count1 = warehouseService.count(lqw);
        map.put("allNum",count1);//总文件数
        LambdaQueryWrapper<Recycle> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(Recycle::getUserId,BaseContext.getCurrentId());
        int count2 = recycleService.count(lqw2);
        map.put("recycleNum",count2);
        return R.success(map);
    }

    @GetMapping("/gettrans")
    public R<String> getUserTrans(){
        User user = userService.getById(BaseContext.getCurrentId());
        if(user.getBanTransfer()==1){
            //被禁用了
            return R.success("NO");
        }
        return R.success("YES");
    }
}
